package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2021-11-02
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    @Override
    public ResponseResult listByName(ChannelDto dto) {
        //根据名称进行分页查询
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //使用mp推荐的lamda表达式的写法
        LambdaQueryWrapper<WmChannel> queryWrapper = Wrappers.lambdaQuery();
        if(StringUtils.isNotBlank(dto.getName())){
            queryWrapper.like(WmChannel::getName,dto.getName());
        }
        //构造分页对象
        IPage<WmChannel> page = new Page<>(dto.getPage(),dto.getSize());
        //返回查询结果
        IPage<WmChannel> page1 = this.page(page,queryWrapper);
        //构建分页结果对象
        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());
    }

    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {
        if(wmChannel==null||StringUtils.isBlank(wmChannel.getName())){
            //如果参数为空,返回错误信息
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据名称判断这个频道是否已经存在
        LambdaQueryWrapper<WmChannel> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName,wmChannel.getName());
        int count = this.count(queryWrapper);
        if (count ==0){
            wmChannel.setCreatedTime(new Date());
            this.save(wmChannel);
            return ResponseResult.okResult();
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
    }
}
